package lk.icta.core.service.impl;

import lk.icta.common.ELandRuntimeException;
import lk.icta.common.ErrorCodes;
import lk.icta.core.dao.AppointmentScheduleDAO;
import lk.icta.core.entity.AppointmentSchedule;
import lk.icta.core.service.AppointmentScheduleManagementService;
import lk.icta.user.common.Permission;
import lk.icta.user.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

/**
 * @author Kusal Samarakoon
 */
public class AppointmentScheduleManagementServiceImpl implements AppointmentScheduleManagementService {

    private static final Logger logger = LoggerFactory.getLogger(AppointmentScheduleManagementServiceImpl.class);
    private final AppointmentScheduleDAO appointmentScheduleDAO;

    public AppointmentScheduleManagementServiceImpl(AppointmentScheduleDAO appointmentScheduleDAO) {
        this.appointmentScheduleDAO = appointmentScheduleDAO;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void addAppointmentSchedule(AppointmentSchedule schedule, User user) {
        logger.debug("Adding a Appointment Schedule {}", schedule.getId());
        if (!user.isAuthorized(Permission.ALIENATION_APPROVAL)) {
            throw new ELandRuntimeException(user.getUsername() + " doesn't have permission to add an appointmentSchedule", ErrorCodes.UNAUTHORIZED_ACCESS);
        } else {
            appointmentScheduleDAO.addAppointmentSchedule(schedule, user);
        }
    }

    @Transactional(propagation = Propagation.NEVER, readOnly = true)
    public List<AppointmentSchedule> getAllAppointmentScheduleByDSDivision(User user) {
        logger.debug("Listing AppointmentSchedule  by {}", user.getUsername());
        List<AppointmentSchedule> scheduleList = appointmentScheduleDAO.getAllAppointmentScheduleByDSDivision(user);
        if (scheduleList != null && scheduleList.size() > 0) {
            return scheduleList;
        }
        return Collections.emptyList();
    }

    @Transactional(propagation = Propagation.NEVER, readOnly = true)
    public AppointmentSchedule findScheduleByApplicationId(User user, long applicationId) {
        List<AppointmentSchedule> scheduleList = appointmentScheduleDAO.findScheduleByApplicationId(user, applicationId);
        if (scheduleList != null && scheduleList.size() > 0) {
            return scheduleList.get(0);
        }
        return null;
    }

    @Transactional(propagation = Propagation.NEVER, readOnly = true)
    public List<AppointmentSchedule> findSchedulesByApplicationId(User user, long applicationId) {
        List<AppointmentSchedule> scheduleList = appointmentScheduleDAO.findSchedulesByApplicationId(user, applicationId);
        if (scheduleList != null && scheduleList.size() > 0) {
            return scheduleList;
        }
        return null;
    }

}
